'use client';

import { useState, useEffect, useCallback } from 'react';

export default function PtzPresets({ 
  channelId, 
  onQueryPresets, 
  onAddPreset, 
  onCallPreset, 
  onDeletePreset,
  disabled = false 
}) {
  const [presets, setPresets] = useState([]);
  const [showInput, setShowInput] = useState(false);
  const [newPresetId, setNewPresetId] = useState('');
  const [loading, setLoading] = useState(false);

  // 获取预置点列表
  const loadPresets = useCallback(async () => {
    if (!onQueryPresets || !channelId) return;
    
    try {
      setLoading(true);
      const data = await onQueryPresets(channelId);
      setPresets(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('获取预置点失败:', error);
      setPresets([]);
    } finally {
      setLoading(false);
    }
  }, [channelId, onQueryPresets]);

  // 组件加载时获取预置点
  useEffect(() => {
    loadPresets();
  }, [loadPresets]);

  // 添加预置点
  const handleAddPreset = useCallback(async () => {
    if (!newPresetId.trim() || !onAddPreset) return;

    const presetId = parseInt(newPresetId.trim());
    if (isNaN(presetId) || presetId < 1 || presetId > 255) {
      alert('预置点编号必须是1-255之间的数字');
      return;
    }

    try {
      setLoading(true);
      await onAddPreset(channelId, presetId);
      setNewPresetId('');
      setShowInput(false);
      // 延迟重新加载，给设备时间处理
      setTimeout(() => {
        loadPresets();
      }, 1000);
    } catch (error) {
      console.error('添加预置点失败:', error);
      alert('添加预置点失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  }, [channelId, newPresetId, onAddPreset, loadPresets]);

  // 调用预置点
  const handleCallPreset = useCallback(async (preset) => {
    if (!onCallPreset) return;

    try {
      setLoading(true);
      await onCallPreset(channelId, preset.presetId);
    } catch (error) {
      console.error('调用预置点失败:', error);
      alert('调用预置点失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  }, [channelId, onCallPreset]);

  // 删除预置点
  const handleDeletePreset = useCallback(async (preset) => {
    if (!onDeletePreset) return;

    if (!confirm(`确定删除预置点 ${preset.presetName || preset.presetId} 吗？`)) {
      return;
    }

    try {
      setLoading(true);
      await onDeletePreset(channelId, preset.presetId);
      // 延迟重新加载
      setTimeout(() => {
        loadPresets();
      }, 1000);
    } catch (error) {
      console.error('删除预置点失败:', error);
      alert('删除预置点失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  }, [channelId, onDeletePreset, loadPresets]);

  const handleCancel = () => {
    setShowInput(false);
    setNewPresetId('');
  };

  const handleShowInput = () => {
    setShowInput(true);
  };

  return (
    <div className={`ptz-presets ${disabled ? 'disabled' : ''}`}>
      <div className="presets-header">
        <h4>预置点管理</h4>
        <button 
          onClick={loadPresets}
          disabled={loading || disabled}
          className="refresh-btn"
          title="刷新预置点列表"
        >
          🔄
        </button>
      </div>

      {loading && (
        <div className="loading-indicator">
          <span>处理中...</span>
        </div>
      )}

      <div className="presets-content">
        {/* 预置点列表 */}
        <div className="presets-list">
          {presets.length > 0 ? (
            presets.map((preset) => (
              <div key={preset.presetId} className="preset-item">
                <span 
                  className="preset-label"
                  onClick={() => handleCallPreset(preset)}
                  title={`点击调用预置点 ${preset.presetName || preset.presetId}`}
                >
                  {preset.presetName || `预置点${preset.presetId}`}
                </span>
                <button
                  className="delete-btn"
                  onClick={() => handleDeletePreset(preset)}
                  disabled={loading}
                  title="删除预置点"
                >
                  ✕
                </button>
              </div>
            ))
          ) : (
            <div className="no-presets">
              暂无预置点
            </div>
          )}
        </div>

        {/* 添加预置点 */}
        <div className="add-preset-section">
          {showInput ? (
            <div className="input-section">
              <div className="input-group">
                <input
                  type="number"
                  min="1"
                  max="255"
                  value={newPresetId}
                  onChange={(e) => setNewPresetId(e.target.value)}
                  placeholder="预置位编号(1-255)"
                  className="preset-input"
                  disabled={loading}
                />
                <button 
                  onClick={handleAddPreset}
                  disabled={loading || !newPresetId.trim()}
                  className="save-btn"
                >
                  保存
                </button>
                <button 
                  onClick={handleCancel}
                  disabled={loading}
                  className="cancel-btn"
                >
                  取消
                </button>
              </div>
              <div className="input-hint">
                请将摄像头调整到要保存的位置，然后输入预置点编号并保存
              </div>
            </div>
          ) : (
            <button 
              onClick={handleShowInput}
              disabled={loading || disabled}
              className="add-btn"
            >
              + 添加预置点
            </button>
          )}
        </div>
      </div>

      <style jsx>{`
        .ptz-presets {
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          padding: 16px;
          margin: 16px 0;
        }

        .ptz-presets.disabled {
          opacity: 0.6;
          pointer-events: none;
        }

        .presets-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        }

        .presets-header h4 {
          margin: 0;
          color: #343a40;
          font-size: 16px;
        }

        .refresh-btn {
          background: none;
          border: 1px solid #dee2e6;
          border-radius: 4px;
          padding: 4px 8px;
          cursor: pointer;
          font-size: 14px;
        }

        .refresh-btn:hover {
          background: #e9ecef;
        }

        .refresh-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .loading-indicator {
          text-align: center;
          padding: 12px;
          color: #6c757d;
          font-size: 14px;
        }

        .presets-content {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }

        .presets-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          min-height: 40px;
        }

        .preset-item {
          display: flex;
          align-items: center;
          background: #ffffff;
          border: 1px solid #dee2e6;
          border-radius: 4px;
          overflow: hidden;
        }

        .preset-label {
          padding: 6px 12px;
          cursor: pointer;
          font-size: 14px;
          color: #495057;
          user-select: none;
          transition: background-color 0.2s;
        }

        .preset-label:hover {
          background: #e3f2fd;
        }

        .delete-btn {
          padding: 6px 8px;
          background: #dc3545;
          color: white;
          border: none;
          cursor: pointer;
          font-size: 12px;
          transition: background-color 0.2s;
        }

        .delete-btn:hover {
          background: #c82333;
        }

        .delete-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .no-presets {
          color: #6c757d;
          font-size: 14px;
          text-align: center;
          padding: 20px;
          font-style: italic;
        }

        .add-preset-section {
          border-top: 1px solid #dee2e6;
          padding-top: 16px;
        }

        .input-section {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .input-group {
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .preset-input {
          flex: 1;
          padding: 8px 12px;
          border: 1px solid #ced4da;
          border-radius: 4px;
          font-size: 14px;
        }

        .preset-input:focus {
          outline: none;
          border-color: #007bff;
          box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }

        .save-btn, .cancel-btn, .add-btn {
          padding: 8px 16px;
          border: 1px solid #dee2e6;
          border-radius: 4px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s;
        }

        .save-btn {
          background: #28a745;
          color: white;
          border-color: #28a745;
        }

        .save-btn:hover {
          background: #218838;
        }

        .save-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .cancel-btn {
          background: #6c757d;
          color: white;
          border-color: #6c757d;
        }

        .cancel-btn:hover {
          background: #5a6268;
        }

        .add-btn {
          background: #007bff;
          color: white;
          border-color: #007bff;
          width: 100%;
        }

        .add-btn:hover {
          background: #0069d9;
        }

        .add-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .input-hint {
          font-size: 12px;
          color: #6c757d;
          font-style: italic;
        }
      `}</style>
    </div>
  );
}